# -*- coding: utf-8 -*-
"""
 * @file main.py
 * @author SDK_TEAM
 * @brief
 * @version 0.1
 * @date 2024-05-31
 * Copyright:
 * © 2018 北京灵汐科技有限公司 版权所有。
 * 注意：以下内容均为北京灵汐科技有限公司原创，未经本公司允许，不得转载，否则将视为侵权；对于不遵守此声明或者其他违法使用以下内容者，本公司依法保留追究权。
 * © 2018 Lynxi Technologies Co., Ltd. All rights reserved.
 * NOTICE: All information contained here is, and remains the property of Lynxi. This file can not
 * be copied or distributed without the permission of Lynxi Technologies Co., Ltd.
"""

import multiprocessing
import signal
import sys
import json
import ipeParamYowov2

sys.path.append("../../../")
from ctypes import *
import argparse
import common.python.common as common
import struct
import pylynchipsdk as sdk
from common.python.plugin_utils import *
from common.python.infer_process import *
from common.python.callback_data_struct import *
import ctypes


# Create a shared boolean value to stop running thread
cancel_flag = multiprocessing.Value("b", False)
pythonapi.PyCapsule_GetPointer.restype = c_void_p
pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p]


def save_boxinfo_cb(params):
    output_path = params[0]
    boxex_info = params[1]
    eos = params[2]
    if eos:
        return 0

    dst_img_size = ctypes.sizeof(Box)
    host_buf_arr = np.ones(dst_img_size, dtype=np.uint8)
    host_buf = sdk.lyn_numpy_to_ptr(host_buf_arr)
    ret = sdk.lyn_memcpy(
        host_buf, boxex_info, dst_img_size, sdk.lyn_memcpy_dir_t.ServerToClient
    )
    common.error_check(ret, "save_boxinfo_cb lyn_memcpy")
    host_buf_c = pythonapi.PyCapsule_GetPointer(host_buf, None)
    c_box = ctypes.cast(host_buf_c, ctypes.POINTER(Box)).contents
    dump_box_json(output_path, c_box)
    return 0


def dump_box_json(output_path, c_box):
    box_dict = {"boxesnum": c_box.boxesnum, "boxes": []}
    for i in range(c_box.boxesnum):
        bbox_instance = c_box.boxes[i]
        bbox_dict = {
            "xmin": bbox_instance.xmin,
            "ymin": bbox_instance.ymin,
            "xmax": bbox_instance.xmax,
            "ymax": bbox_instance.ymax,
            "score": bbox_instance.score,
            "label": bbox_instance.label.decode("utf-8"),
        }
        box_dict["boxes"].append(bbox_dict)

    # Serialize the dictionary to JSON
    with open(output_path, "a", encoding="utf-8") as f:
        f.seek(0, os.SEEK_END)
        file_size = f.tell()
        if file_size < 500 * 1024 * 1024:
            json.dump(box_dict, f, indent=2, ensure_ascii=False)
            f.write("\n")
        else:
            print("only support 500M.", output_path, "now file size:", file_size)

def lyn_free_callback(params):
    for p in params:
        common.error_check(sdk.lyn_free(p))
    return 0

class yowov2(infer_process):
    def __init__(self, attr):
        super().__init__(attr)
        self.batch_size = self.model_desc.inputTensorAttrArray[0].batchSize
        self.model_width = self.model_desc.inputTensorAttrArray[0].dims[3]
        self.model_height = self.model_desc.inputTensorAttrArray[0].dims[2]
        self.clip_size = self.model_desc.inputTensorAttrArray[0].dims[1]
        (
            self.resize_width,
            self.resize_height,
            self.pad_x,
            self.pad_y,
        ) = self.set_padding_data(
            self.vdec_out_info.width,
            self.vdec_out_info.height,
            self.model_width,
            self.model_height,
        )

        self.first_frame = True

        self.apu_input_size = (
            self.clip_size
            * self.model_width
            * self.model_height
            * self.model_desc.inputTensorAttrArray[0].dims[4]
        )

        self.apu_input_ptr, ret = sdk.lyn_malloc(self.apu_input_size)
        common.error_check(ret)

        self.ipe_output_size = (
            self.model_width
            * self.model_height
            * self.model_desc.inputTensorAttrArray[0].dims[4]
        )
        if self.ipe_output_mem_pool:
            self.ipe_output_mem_pool.free_buffers()

        self.ipe_output_mem_pool = bufferpool.buffer_pool(
            self.ipe_output_size * self.batch_size, 5
        )

        self.box_apu_ptr, ret = sdk.lyn_malloc(ctypes.sizeof(Box))
        common.error_check(ret)

        self.post_plugin, ret = sdk.lyn_plugin_register(attr.post_plugin)
        common.error_check(ret, "lyn_plugin_register")

        self.osd_plugin, ret = sdk.lyn_plugin_register(attr.osd_plugin)
        common.error_check(ret, "lyn_plugin_register")


    def set_padding_data(self, video_width, video_heigh, model_width, model_height):
        
        self.ipeYowov2 = ipeParamYowov2.IpeParamYowov2(model_width, model_height)
        self.ipeYowov2.set_img_info(video_width, video_heigh,
                            sdk.lyn_pixel_format_t.LYN_PIX_FMT_NV12)

        return 0,0,0,0

    def ipe_process(self, cb_data: framepool_cb_data):
        sdk.lyn_set_current_context(self.get_ctx())
        ipe_out_data = self.ipe_output_mem_pool.pop()
        self.ipeYowov2.calc_param(self.ipe_stream, cb_data.frame.data, ipe_out_data)

        return ipe_out_data

    def apu_process(self, ipe_out_data):
        sdk.lyn_set_current_context(self.get_ctx())
        # 等待IPE处理完成
        ret = sdk.lyn_record_event(self.ipe_stream, self.ipe_event)
        common.error_check(ret, "lyn_record_event")
        ret = sdk.lyn_stream_wait_event(self.apu_stream, self.ipe_event)
        common.error_check(ret, "lyn_stream_wait_event")

        #整合clip
        if self.first_frame:
            target_seek = self.apu_input_ptr
            for i in range(self.clip_size):
                ret = sdk.lyn_memcpy_async(
                    self.apu_stream,
                    target_seek,
                    ipe_out_data,
                    self.ipe_output_size,
                    sdk.lyn_memcpy_dir_t.ServerToServer,
                )
                common.error_check(ret, "lyn_memcpy clip init")

                target_seek = sdk.lyn_addr_seek(target_seek, self.ipe_output_size)

            self.first_frame = False
        else:
            target_seek = self.apu_input_ptr
            source_seek = self.apu_input_ptr
            #每一块往前挪一下，空出最后一块
            for i in range(1, self.clip_size):
                source_seek = sdk.lyn_addr_seek(source_seek, self.ipe_output_size)

                ret = sdk.lyn_memcpy_async(
                    self.apu_stream,
                    target_seek,
                    source_seek,
                    self.ipe_output_size,
                    sdk.lyn_memcpy_dir_t.ServerToServer,
                )
                common.error_check(ret, "lyn_memcpy clip move")

                target_seek = sdk.lyn_addr_seek(target_seek, self.ipe_output_size)

            ret = sdk.lyn_memcpy_async(
                self.apu_stream,
                source_seek, #最后一个填充新的
                ipe_out_data,
                self.ipe_output_size,
                sdk.lyn_memcpy_dir_t.ServerToServer,
            )
            common.error_check(ret, "lyn_memcpy clip append")


        apu_output_data = self.apu_output_mem_pool.pop()
        ret = sdk.lyn_execute_model_async(
            self.apu_stream,
            self.get_model(),
            self.apu_input_ptr,
            apu_output_data,
            self.batch_size,
        )
        common.error_check(ret, "lyn_execute_model_async")

        ret = sdk.lyn_stream_add_callback(
            self.apu_stream,
            free_to_pool_callback,
            [self.ipe_output_mem_pool, ipe_out_data],
        )
        common.error_check(ret, "lyn_stream_add_callback")
        common.print_frame_rate(self.get_channel_info())
        return apu_output_data

    def before_ctx_destroy(self):
        self.ipeYowov2.destory()

        common.error_check(sdk.lyn_free(self.apu_input_ptr))
        common.error_check(sdk.lyn_free(self.box_apu_ptr))
        ret = sdk.lyn_plugin_unregister(self.osd_plugin)
        ret = sdk.lyn_plugin_unregister(self.post_plugin)
        common.error_check(ret, "lyn_plugin_unregister")

    def plugin_process(self, apu_output_data, cb_data):
        ret = sdk.lyn_record_event(self.apu_stream, self.apu_event)
        common.error_check(ret, "lyn_record_event")
        ret = sdk.lyn_stream_wait_event(self.plugin_stream, self.apu_event)
        common.error_check(ret, "lyn_stream_wait_event")

        pythonapi.PyCapsule_GetPointer.restype = c_void_p
        pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p]

        frame_data_ptr = pythonapi.PyCapsule_GetPointer(cb_data.frame.data, None)
        apu_data_ptr_c = pythonapi.PyCapsule_GetPointer(apu_output_data, None)
        box_apu_ptr_c = pythonapi.PyCapsule_GetPointer(self.box_apu_ptr, None)

        post_para = YowoPostInfo_t()
        post_para.img_width = self.codec_para.width
        post_para.img_height = self.codec_para.height
        post_para.conf_threshold = 0.1
        post_para.nms_threshold = 0.5
        post_para.vis_threshold = 0.3
        post_para.model_input_h = self.model_height
        post_para.model_input_w = self.model_width
        post_para.model_output_len = len(self.model_desc.outputTensorAttrArray)
        post_para.output_tensor = apu_data_ptr_c
        post_para.boxesInfo = box_apu_ptr_c


        post_para_s = ctypes.string_at(
            ctypes.addressof(post_para), ctypes.sizeof(post_para)
        )
        ret = sdk.lyn_plugin_run_async(
            self.plugin_stream,
            self.post_plugin,
            "lynYowoPostProcess",
            post_para_s,
            ctypes.sizeof(YowoPostInfo_t),
        )
        common.error_check(ret, "lyn_plugin_run_async")

        if self.attr.show_type == 2:
            ret = sdk.lyn_stream_add_callback(
                self.plugin_stream,
                save_boxinfo_cb,
                [self.attr.output_path, self.box_apu_ptr, cb_data.frame.eos],
            )
        else:
            osd_para = struct.pack(
                "1P3i1P4i",
                box_apu_ptr_c,
                self.codec_para.width,
                self.codec_para.height,
                sdk.lyn_pixel_format_t.LYN_PIX_FMT_NV12,
                frame_data_ptr,
                24,
                4,
                2,
                4,
            )
            common.error_check(
                sdk.lyn_plugin_run_async(
                    self.plugin_stream, self.osd_plugin, "lynDrawBoxAndText", osd_para, len(osd_para)
                )
            )

        ret = sdk.lyn_stream_add_callback(
            self.plugin_stream,
            free_to_pool_callback,
            [self.apu_output_mem_pool, apu_output_data],
        )
        common.error_check(ret, "lyn_stream_add_callback")

    def run(self, attr: infer_process_attr):
        super().run(attr)


def main(args, video_frame) -> None:
    attr = infer_process_attr()
    attr.url = args.input_path
    if args.show_type == 1:
        attr.output_path = common.append_text_to_filename(
            common.change_file_extension(args.input_path, ".264"),
            f"_device_{args.device_id}_channel_{args.channel_id}",
        )
    elif args.show_type == 2:
        attr.output_path = common.append_text_to_filename(
            common.change_file_extension(args.input_path, ".json"),
            f"_device_{args.device_id}_channel_{args.channel_id}",
        )
    if not os.path.isfile(attr.url):
        attr.output_path = attr.output_path.replace("/", "_").replace(":", "_")
    if os.path.exists(attr.output_path):
        os.remove(attr.output_path)
    attr.device_id = args.device_id
    attr.chan_id = args.channel_id
    attr.plugin_path = args.osd_plugin
    attr.model_path = args.model_path
    attr.show_type = args.show_type
    attr.video_frame = video_frame
    attr.osd_plugin = args.osd_plugin
    attr.post_plugin = args.post_plugin
    if not attr.url:
        raise ValueError("input file miss!!!")
    if attr.show_type == 1 and not attr.output_path:
        raise ValueError("unspecified output path!!!")
    yowov2_worker = yowov2(attr)
    yowov2_worker.run(cancel_flag)
    yowov2_worker.close()


def cancel_process(signum, frame):
    global cancel_flag
    cancel_flag.value = True


if __name__ == "__main__":
    argparser = argparse.ArgumentParser(description="python3 main.py ")
    argparser.add_argument("-m", "--model_path", type=str, help="model file path")
    argparser.add_argument("-i", "--input_path", help="input video path or stream url")
    argparser.add_argument("-p", "--post_plugin", type=str, help="plugin path")
    argparser.add_argument("-o", "--osd_plugin", type=str, help="plugin path")
    argparser.add_argument(
        "-d",
        "--device_id",
        type=str,
        default="0",
        help='Comma-separated list of device ids, e.g., "0,1"',
    )
    argparser.add_argument("-s", "--show_type", type=int, default=0, help="show type")
    argparser.add_argument(
        "-c", "--channel_num", type=int, default=1, help="channel_num"
    )
    argparser.add_argument(
        "-j", "--config_file", type=str, default=None, help="config path"
    )

    signal.signal(signal.SIGINT, cancel_process)
    args = argparser.parse_args()
    channel_infos = get_channel_infos(args)
    start_process(main, channel_infos, cancel_flag)
